#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QTcpSocket>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    pServer = new QTcpServer(this);
    pServer->listen(QHostAddress::Any,9000);
    //当有新的链接信号时调用对应的槽函数
    connect(pServer,&QTcpServer::newConnection,this,[&](){
        qDebug()<<"有客户端链接上了"<<endl;
        QTcpSocket * pSocket = pServer->nextPendingConnection();
        socketList.push_back(pSocket);

        //把QTcpSocket的可以读数据的信号和lambda表达式连接
        connect(pSocket,&QTcpSocket::readyRead,this,[=]{
            char buf[128];
            pSocket->read(buf,sizeof(buf));//读取网络发来的数据
            qDebug()<<buf<<endl;
            //遍历链表中的每一个SOCKET，把消息转发给所有的SOCKET
            for (int i = 0; i < socketList.size(); ++i) {
                socketList[i]->write(buf,sizeof(buf));
            }
        });

        //把QTcpSocket的断开连接的信号和lambda表达式连接
        connect(pSocket,&QTcpSocket::disconnected,this,[=]{
            qDebug()<<"我是服务器，客户端断开连接了";
            pSocket->close();
        });


        char buf[128] = "hello!";
        pSocket->write(buf,sizeof(buf));
//        pSocket->close();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
